package com.moon.controller;

import com.moon.anno.ReCommit;
import com.moon.dao.TAuctionMapper;
import com.moon.dto.TUser;
import com.moon.entity.TAuction;
import com.moon.es.EsDataWriter;
import com.moon.es.EsProductRepository;
import com.moon.service.AuctionService;
import com.moon.utils.IdWorker;
import com.moon.utils.UserUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@RequestMapping("/auction")
@RestController
public class AuctionController {

    @Autowired
    @Qualifier("idWorker1")
    IdWorker idWorker1;

    @Autowired
    TAuctionMapper auctionMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    AuctionService auctionService;

    @Autowired
    @Qualifier("esProduct")
    EsDataWriter esDataWriter;

    @Autowired
    EsProductRepository esProductRepository;

    @ReCommit(timeout = 10000)
    @RequestMapping("/insert")
    public String insert(@RequestParam("productId") long productId, @RequestParam("basePrice") String basePrice, @RequestParam("stepPrice") String stepPrice) {
        return auctionService.insert(productId, basePrice, stepPrice);
    }

    @RequestMapping("/start")
    public String start(@RequestBody TAuction auction){
        return auctionService.startAuction(auction);

    }
    @ReCommit(timeout = 10000)
    @RequestMapping("join")
    public String join(@RequestParam("id") Long id, HttpServletRequest req){
        TUser tuser = UserUtils.getCurrUserFromHeader("token", TUser.class, req);
        auctionService.join(id,tuser.getId());
        return "success";
    }
    @ReCommit(timeout = 10000)
    @RequestMapping("bidding")
    public String bidding(@RequestParam("id") Long id, @RequestParam("newPrice") BigDecimal newPrice, HttpServletRequest req){
        TUser tuser = UserUtils.getCurrUserFromHeader("token", TUser.class, req);

        TAuction tAuction = auctionMapper.selectByPrimaryKey(id);
        if(tAuction.getStatus()!=1){
            return "拍卖已结束哦";
        }
        BigDecimal tempPrice = newPrice;
        tempPrice= tempPrice.subtract(tAuction.getTopPrice());
        if(tempPrice.compareTo(BigDecimal.ZERO) < 1){
            return "已有更高的价格，请重新出价";
        }
        tempPrice= tempPrice.divide(tAuction.getStepPrice());
        if(new BigDecimal(tempPrice.intValue()).compareTo(tempPrice)!=0){
            return "参数异常，请稍后再试";
        }
        return auctionService.bidding(tAuction,tuser,newPrice);
    }

}
